package com.quanxiaoha.weblog.web.controller;

import com.quanxiaoha.weblog.common.Response;
import com.quanxiaoha.weblog.common.domain.dos.CommentDO;
import com.quanxiaoha.weblog.web.model.vo.article.AddCommentReqVO;
import com.quanxiaoha.weblog.web.model.vo.article.AddCommentRespVO;
import com.quanxiaoha.weblog.web.model.vo.article.FindCommentsReqVO;
import com.quanxiaoha.weblog.web.service.CommentService;
import com.quanxiaoha.weblog.web.service.BlogSettingService;
import com.quanxiaoha.weblog.common.domain.dos.BlogSettingDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;
    
    @Autowired
    private BlogSettingService blogSettingService;

    /**
     * 添加评论
     *
     * @param addCommentReqVO
     * @return
     */
    @PostMapping("/add")
    public Response addComment(@RequestBody @Valid AddCommentReqVO addCommentReqVO, HttpServletRequest request) {
        // 初始化昵称和头像为用户输入的值
        String nickname = addCommentReqVO.getNickname();
        String avatar = null;
        
        // 检查用户是否已登录
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        boolean isAuthenticated = authentication != null && authentication.isAuthenticated() 
            && !"anonymousUser".equals(authentication.getPrincipal());
        
        // 如果用户已登录，使用博客设置中的作者名和头像
        if (isAuthenticated) {
            // 获取博客设置信息
            BlogSettingDO blogSettingDO = blogSettingService.getOne(null);
            if (blogSettingDO != null) {
                nickname =blogSettingDO.getAuthor();
                avatar = blogSettingDO.getAvatar();
            }
        }
        
        // 如果未登录或者博客设置信息为空，则使用随机头像
        if (avatar == null) {
            // 随机分配头像
            String[] avatars = {
                    "https://java-file-spring.oss-cn-beijing.aliyuncs.com/av.png",
                    "https://java-file-spring.oss-cn-beijing.aliyuncs.com/96486cfc-8fdb-46d4-85a9-329efc84f4dd.png",
                    "https://java-file-spring.oss-cn-beijing.aliyuncs.com/84b2d6ca-a54a-4ecf-ada1-b78c41022ed4.png",
                    "https://java-file-spring.oss-cn-beijing.aliyuncs.com/72978968-4d1d-4179-99f2-752f7a34687d.svg",
                    "https://java-file-spring.oss-cn-beijing.aliyuncs.com/05a39c5c-3901-4a7f-b1c2-fa9a2698d0e1.png"
            };

            int randomIndex = (int) (Math.random() * avatars.length);
            avatar = avatars[randomIndex];
        }

        // 获取用户IP地址
        String ipAddress = getClientIpAddress(request);

        CommentDO commentDO = CommentDO.builder()
                .articleId(addCommentReqVO.getArticleId())
                .parentId(addCommentReqVO.getParentId())
                .content(addCommentReqVO.getContent())
                .nickname(nickname) // 使用处理后的昵称
                .avatar(avatar) // 使用处理后的头像
                .ipAddress(ipAddress) // 设置IP地址
                .createTime(new Date()) // 设置创建时间
                .status(1) // 默认评论区是启用的
                .isChecked(0) // 默认未审核
                .build();

        CommentDO result = commentService.addComment(commentDO);

        AddCommentRespVO respVO = AddCommentRespVO.builder()
                .id(result.getId())
                .articleId(result.getArticleId())
                .parentId(result.getParentId())
                .content(result.getContent())
                .nickname(result.getNickname())
                .avatar(result.getAvatar())
                .ipAddress(result.getIpAddress()) // 返回IP地址
                .createTime(result.getCreateTime())
                .build();

        return Response.success(respVO);
    }

    /**
     * 获取文章评论列表
     *
     * @param findCommentsReqVO
     * @return
     */
    @PostMapping("/list")
    public Response<List<AddCommentRespVO>> findComments(@RequestBody @Valid FindCommentsReqVO findCommentsReqVO) {
        List<CommentDO> commentDOS = commentService.getCommentsByArticleId(findCommentsReqVO.getArticleId());

        List<AddCommentRespVO> respVOS = commentDOS.stream().map(commentDO ->
                AddCommentRespVO.builder()
                        .id(commentDO.getId())
                        .articleId(commentDO.getArticleId())
                        .parentId(commentDO.getParentId())
                        .content(commentDO.getContent())
                        .nickname(commentDO.getNickname())
                        .avatar(commentDO.getAvatar())
                        .ipAddress(commentDO.getIpAddress()) // 返回IP地址
                        .createTime(commentDO.getCreateTime())
                        .build()
        ).collect(Collectors.toList());

        return Response.success(respVOS);
    }

    /**
     * 获取文章评论数
     *
     * @param findCommentsReqVO
     * @return
     */
    @PostMapping("/count")
    public Response getCommentCount(@RequestBody @Valid FindCommentsReqVO findCommentsReqVO) {
        Long count = commentService.getCommentCountByArticleId(findCommentsReqVO.getArticleId());
        return Response.success(count);
    }

    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
// 可能有多个IP地址，取第一个非unknown的有效IP字符串
            int index = ip.indexOf(',');
            if (index != -1) {
                ip = ip.substring(0, index);
            }
        } else {
            ip = request.getHeader("X-Real-IP");
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}